<?php
class WPaymentAuthorizenetDirect extends USystemWorklet
{
	public $paymentAction = 'authorization';
	public $formWorklet;
	
	public function accessRules()
	{
		return array(
			array('deny', 'users'=>array('?'))
		);
	}
	
	public function run($items,$orderId=null,$options=array())
	{
		include_once(dirname(__FILE__).'/../components/anet_php_sdk/AuthorizeNet.php');
		
		$amount = 0;
		foreach($items as $key=>$val)
		{
			if(is_array($val))
				$amount+= $val['price']*$val['quantity'];
		}
		
		$month = $this->formWorklet->model->ccexp['month'];
		$year = $this->formWorklet->model->ccexp['year'];
		$expdate = (strlen($month)<2?'0'.$month:$month)
			. substr($year,2);
		$location = wm()->get('location.helper')->locationToData($this->formWorklet->model->location);
		
		$transaction = new AuthorizeNetAIM($this->param('apiLogin'), $this->param('apiTransactionKey')); 
		if(!$this->param('sandbox'))
			$transaction->setSandbox(false);
		$transaction->amount = $amount;
		$transaction->card_num = $this->formWorklet->model->ccnum;
		$transaction->card_code = $this->formWorklet->model->cccode;
		$transaction->exp_date = $month.'/'.$year; 
		$transaction->address = $this->formWorklet->model->address;
		$transaction->country = $location['country'];
		$transaction->state = $location['state'];
		$transaction->city = $location['city'];
		$transaction->zip = $this->formWorklet->model->zip;
		$transaction->first_name = $this->formWorklet->model->firstName;
		$transaction->last_name = $this->formWorklet->model->lastName;		
		 
		if($this->paymentAction == 'authorization')
			$response = $transaction->authorizeOnly();
		else
			$response = $transaction->authorizeAndCapture();
			
		if($response->approved)
		{
			if($this->paymentAction == 'authorization')
				wm()->get('payment.order')->authorize($orderId,$response->transaction_id);
			else
				wm()->get('payment.order')->charge($orderId,$response->transaction_id);
		}
		else
		{
			$w = wm()->get('payment.checkout');
			$w->form->model->addError('type',$response->error_message);
		}
	}
}